package com.lvyong.hcar;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import android.util.Log;
import android.view.View;

import androidx.core.app.ActivityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.lvyong.hcar.databinding.ActivityMainBinding;

import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    BluetoothAdapter mBluetoothAdapter;
    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

    ConnectThread connectThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        binding.btnS.setOnClickListener(this);
        binding.btnF.setOnClickListener(this);
        binding.btnR.setOnClickListener(this);
        binding.btnB.setOnClickListener(this);
        binding.btnL.setOnClickListener(this);
        setContentView(binding.getRoot());
        initPermission();
        initBluetooth();
    }

    private void initPermission() {
        List<String> mPermissionList = new ArrayList<>();
        // Android 版本大于等于 12 时，申请新的蓝牙权限
        mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
        mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
        mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
            mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
            //根据实际需要申请定位权限
            //mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            //mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        } else {
            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        ActivityCompat.requestPermissions(this, mPermissionList.toArray(new String[0]), 1);
    }

    public Set<BluetoothDevice> getConnetedDevices() {
        if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return mBluetoothAdapter.getBondedDevices();
            }
            return mBluetoothAdapter.getBondedDevices();
        }
        return null;
    }


    private void initBluetooth() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            // 设备不支持蓝牙
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            startActivityForResult(intent, 1);
        }

        Set<BluetoothDevice> connetedDevices = getConnetedDevices();
        for (BluetoothDevice device : connetedDevices) {
            Log.v("name", "bleName ; " + device.getName());

            if(device.getName().equalsIgnoreCase("lvyong"))
            {
                Toast.makeText(MainActivity.this, "bleName ; " + device.getName(), Toast.LENGTH_SHORT).show();
                connectThread = new ConnectThread(device);
                connectThread.start();
            }
        }

        //第一步：注册广播
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);//不要忘了在onDestory中unregister
    }

    //第三步:接收广播
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //发现了设备
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                Toast.makeText(MainActivity.this, "发现设备", Toast.LENGTH_SHORT).show();
                //从Intent中获取设备的BluetoothDevice对象
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                Log.v("name", "bleName ; " + device.getName());
                Toast.makeText(MainActivity.this, "bleName ; " + device.getName(), Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        return true;
    }

    private void sendChar(int a)
    {
        try {
            connectThread.getmSocket().getOutputStream().write(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onClick(View view) {
        switch(view.getId())
        {
            case R.id.btn_s:
                sendChar('s');
                break;
            case R.id.btn_f:
                sendChar('f');
                break;
            case R.id.btn_l:
                sendChar('l');
                break;
            case R.id.btn_b:
                sendChar('b');
                break;
            case R.id.btn_r:
                sendChar('r');
                break;
        }
    }

    public class ConnectThread extends Thread {
        private BluetoothDevice mDevice;
        private BluetoothSocket mSocket;

        public BluetoothSocket getmSocket() {
            return mSocket;
        }

        public void setmSocket(BluetoothSocket mSocket) {
            this.mSocket = mSocket;
        }

        @SuppressLint("MissingPermission")
        public ConnectThread(BluetoothDevice device) {
            BluetoothSocket temp = null;
            mDevice = device;
            try {

                temp = mDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            mSocket = temp;
        }

        @SuppressLint("MissingPermission")
        @Override
        public void run() {
            super.run();
            try {
                //通过socket连接设备，这是一个阻塞操作，知道连接成功或发生异常
//                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
//                    // TODO: Consider calling
//                    //    ActivityCompat#requestPermissions
//                    // here to request the missing permissions, and then overriding
//                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                    //                                          int[] grantResults)
//                    // to handle the case where the user grants the permission. See the documentation
//                    // for ActivityCompat#requestPermissions for more details.
//                    return;
//                }
                mSocket.connect();
                mSocket.getOutputStream().write('f');
                try {
                    sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mSocket.getOutputStream().write('s');

            } catch (IOException e) {
                //无法连接，关闭socket并且退出
                try {
                    mSocket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            //管理连接(在独立的线程)
            // manageConnectedSocket(mmSocket);
        }
        /**
         * 取消正在进行的链接，关闭socket
         */
        public void cancel() {
            try {
                mSocket.close();
            } catch (IOException e) { }
        }
    }
}